<template>
  <div class="step-2 step-wrap">
    <div class="step-content">
      <p class="step-title">刻意练习</p>
      <div class="step-text">
        <div class="timer-point-placement">
          <div ref="readyPoint" id="readyPoint" class="timer-point">
            <span></span> <span></span> <span></span>
          </div>
        </div>
        <div class="step-mic" v-show="playSpeed === 5">
          <img src="~assets/reverse/mic.png" alt="" />
        </div>
        <div class="step-mic" v-show="playSpeed === 4 && titleHidden">
          <img src="~assets/reverse/mic.png" alt="" />
        </div>
        <div v-show="+playSpeed === 3 || (!titleHidden && +playSpeed === 4)">
          <p v-show="playSpeed !== 5" class="scene-title">
            <a-popover
              transitionName=""
              v-for="(word, i) in renderHtml"
              :key="word + i"
              overlayClassName="lookup-popover"
              placement="bottom"
              :visible="visibles[i]"
              :destroyTooltipOnHide="true"
              trigger="click"
            >
              <span
                :yxp_attr="viLock?'disable':''" class="synclock"
                @click="checkWord(word, i)"
                :id="`step5-word${i}`"
                :class="{ 'keys-words': keysIndex.includes(i) }"
                >{{ word }}</span
              >
              <div slot="content">
                <div class="lookup-content">
                  <div class="title">
                    {{ translate.prototype_word || translate.select_word }}
                    <img
                      v-show="translate.prototype_word"
                      class="icon-img"
                      @click.stop="translateVoice"
                      src="~assets/reverse/audio-play1.png"
                      alt=""
                    />
                  </div>
                  <div class="translate">
                    {{ translate.translate || "未找到该生词" }}
                  </div>
                  <div class="btn-group">
                    <a
                      class="addword"
                      :disabled="!translate.prototype_word"
                      @click.stop="addWord"
                      ><img
                        class="icon-img"
                        src="~assets/reverse/add1.png"
                        alt=""
                      />添加生词</a
                    >
                    <a @click="translateDetail"
                      ><img
                        class="icon-img"
                        src="~assets/reverse/detail1.png"
                        alt=""
                      />单词详解</a
                    >
                  </div>
                </div>
              </div>
            </a-popover>
          </p>
          <p
            v-show="playSpeed !== 5"
            class="scene-translation"
            :class="{ 'scene-hidden': tabKey === 5 }"
          >
            {{ data.translation }}
          </p>
        </div>
      </div>
      <div class="play-btn step-5">
        <template v-if="playing">
          <img
            @click="playVoice('pause')"
            src="~assets/reverse/pause-round.png"
            alt=""
          />
        </template>
        <template v-else>
          <img
            @click="playVoice('play')"
            src="~assets/reverse/voice-round.png"
            alt=""
          />
        </template>
      </div>
    </div>
    <div class="step2-bottom step5-bottom step-bottom">
      <div class="voice-wrap">
        <span class="play-time">{{ seekDuration | mmssFilter }}</span>
        <a-slider
          :tipFormatter="null"
          class="voice-range"
          :value="sliderPercentage"
        ></a-slider>
        <span class="all-time">{{ audioDuration | mmssFilter }}</span>
        <span class="play-num">{{ overNum }}</span>
        <div class="voice-rate">
          <span :class="{ active: playSpeed == 3 }" @click="changeRate(3)"
            >变频1</span
          >
          <span :class="{ active: playSpeed == 4 }" @click="changeRate(4)"
            >变频2</span
          >
          <span :class="{ active: playSpeed == 5 }" @click="changeRate(5)"
            >变频3</span
          >
        </div>
      </div>
      <div class="tab-controll">
        <img
          @click="changeTab('pre')"
          src="~assets/reverse/left-arrow-round.png"
          alt=""
        />
        <span>全程跟读</span>
        <img
          @click="completeConfirm"
          src="~assets/reverse/complete.png"
          alt=""
        />
      </div>
    </div>
    <Timetips></Timetips>
  </div>
</template>

<script>
import { Slider, Popover } from "ant-design-vue";
import { checkWord, addWord } from "@/services/reverse";
import { SUCCESS_CODE } from "@/utils/const";
import { mapState, mapMutations } from "vuex";
import Timetips from "@/components/Timetips";
import { Howl } from "howler";
import _ from "lodash";
import $ from "jquery";

let completePng = require("assets/reverse/complete-shadow.png");
export default {
  components: {
    ASlider: Slider,
    APopover: Popover,
    Timetips
  },
  data() {
    return {
      keysIndex: [],
      viLock: false,
      lastvi: "",
      visibles: {},
      data: {},
      translate: {},
      keysWords: [],
      voice_rate: [],
      titleHidden: false,
      audio: {},
      playing: false,
      audioDuration: 0,
      seekDuration: 0,
      seekTimer: null,
      readyTimer: null,
      playCurrentNum3: 0, // 当前播放次数 变频单独次数
      playCurrentNum4: 0, // 当前播放次数
      playCurrentNum5: 0, // 当前播放次数
      playSpeed: 3, // 变频的值 对应 voice_rate
    };
  },
  props: {
    renderData: {
      type: Object,
    },
    tabKey: {
      type: Number,
    },
    sentenceCurrent: {
      type: Object,
    },
  },
  computed: {
    ...mapState({
      grammarExplainVisible: (state) => state.grammarExplainVisible,
    }),
    renderHtml: function() {
      return this.data.title.split(" ");
    },
    sliderPercentage: function() {
      return Math.ceil((this.seekDuration / this.audioDuration) * 100);
    },
    overNum: function() {
      return this.voice_rate.length - this[`playCurrentNum${this.playSpeed}`];
    },
  },
  watch: {
    renderData: {
      handler: function(val) {
        let current = val.list.find((v) => v.id === this.sentenceCurrent.id);
        this.data = current;
        this.voice_rate = val[`voice_rate_${this.playSpeed}`];
        this.keysWords = _.flatten(
          current.keys_words.split(",").map((v) => v.split(" "))
        );
        let tmp = this.data.title.replace(
          new RegExp(`(${current.keys_words.split(",").join("|")})`, "ig"),
          (w) => {
            return `##${w.split(" ").join("## ##")}##`;
          }
        );
        tmp = tmp.split(" ");
        for (let i in tmp) {
          if (/^##.+##$/.test(tmp[i])) {
            this.keysIndex.push(Number(i));
          }
        }
      },
      immediate: true,
      deep: true,
    },
    tabKey: function(val) {
      console.log(val);
    },
    grammarExplainVisible(val) {
      if (val) {
        this.audio.pause();
        clearInterval(this.readyTimer);
        this.$refs.readyPoint.style.display = "none";
      }
    },
  },
  methods: {
    ...mapMutations(["setTranslateModal"]),
    outPopClick(oi) {
      if (typeof oi == "object") {
        if (this.visibles[this.lastvi] == true) {
          $(".ant-popover-open").trigger("click");
        }
      } else {
        for (let i in this.visibles) {
          if (typeof oi == "string" && oi == i) continue;
          this.visibles[i] = false;
        }
      }
    },
    changeTab(cmd) {
      this.audio.pause();
      this.$emit("changeTab", cmd);
      clearInterval(this.readyTimer);
      this.$refs.readyPoint.style.display = "none";
    },
    replaceText(word) {
      const pattern = /[^a-zA-Z] | '/g;
      return word.replace(pattern, "");
    },
    checkWord(value, i) {
      i = Number(i).toString();
      this.outPopClick(i);
      this.lastvi = i;
      if (!value || this.viLock) return;
      this.viLock = true;
      checkWord({ word: value }).then((res) => {
        this.translate = res.data;
        this.visibles[i] = !this.visibles[i];
        this.viLock = false;
      });
    },
    addWord() {
      addWord({
        prototype_word: this.translate.prototype_word,
        select_word: this.translate.select_word,
        question_type: 3,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
        }
      });
    },
    translateVoice() {
      let audio = document.getElementById("reverse-audio");
      audio.src = this.translate.project_voice;
      this.audio.pause();
      audio.play();
    },
    translateDetail() {
      this.setTranslateModal({
        visible: true,
        word: this.translate.select_word,
      });
      document.getElementById("app").click();
    },
    readyFun() {
      let time = 0;
      if (this.readyTimer) {
        clearInterval(this.readyTimer);
      }
      this.$refs.readyPoint.style.display = "block";
      let points = this.$refs.readyPoint.children;
      points.forEach((item) => (item.style.visibility = "visible"));
      return new Promise((rev) => {
        this.readyTimer = setInterval(() => {
          time += 200;
          let totalReadyTime =
            this.voice_rate[this[`playCurrentNum${this.playSpeed}`]].time *
            1000;
          if (time >= totalReadyTime * (1 / 3)) {
            points[2].style.visibility = "hidden";
          }
          if (time >= totalReadyTime * (2 / 3)) {
            points[1].style.visibility = "hidden";
          }
          if (time >= totalReadyTime) {
            points[2].style.visibility = "visible";
            points[1].style.visibility = "visible";
            this.$refs.readyPoint.style.display = "none";
          }
          if (time > totalReadyTime) {
            rev(true);
            clearInterval(this.readyTimer);
          }
        }, 200);
      });
    },
    async playVoice(status) {
      if (this.overNum === 0 && status === "autoPlay") return;
      if (this.overNum === 0) {
        this[`playCurrentNum${this.playSpeed}`] = 0;
      }
      let playCurrent = this.voice_rate[
        this[`playCurrentNum${this.playSpeed}`]
      ];
      if (status === "play" || status === "autoPlay") {
        await this.readyFun();
        this.audio.rate(playCurrent.speed);
        this.audio.play();
      } else {
        this.audio.pause();
      }
    },
    rangeChange(value) {
      this.seekDuration = (value / 100) * this.audioDuration;
      this.audio.seek((value / 100) * this.audioDuration);
    },
    changeRate(rate) {
      this.playSpeed = rate;
      this.voice_rate = this.renderData[`voice_rate_${rate}`];
      // 支持多音频播放所以先停掉吧  目前没发现问题
      this.audio.stop();
      this.playVoice("play");
    },
    completeConfirm() {
      this.$yxpConfirm({
        msg: `<img width="223" style="margin: -20px 0 -30px;" src="${completePng}" alt=""/>
             <p>已完成本句学习，开始检测吗?</p>
            `,
        html: true,
        noBtnText: "返回",
        yesBtnText: "检测",
      })
        .then(() => {
          this.$router.push("/reverse/studyed");
        })
        .catch(() => {});
    },
  },
  created() {
    document.body.addEventListener("click", this.outPopClick);
  },
  mounted() {
    let vm = this;
    this.audio = new Howl({
      src: [this.data.voice],
      html5: true,
      onplay: function() {
        //sound playing
        vm.playing = true;

        vm.seekTimer = setInterval(() => {
          vm.seekDuration = this.seek();
        }, 1000);
      },
      onload: function() {
        vm.audioDuration = this.duration();
      },
      onpause: function() {
        clearInterval(vm.seekTimer);
        vm.playing = false;
      },
      onend: function() {
        console.log("end");
        vm.playing = false;
        vm[`playCurrentNum${vm.playSpeed}`] += 1;
        // 暂时排查不出问题，end 时候先手动set 为 100%
        vm.seekDuration = this.duration();
        clearInterval(vm.seekTimer);
        vm.$nextTick(() => {
          // ============英文显示逻辑先放这吧=============
          if (vm.playSpeed === 4 && vm.playCurrentNum4 !== 0) {
            vm.titleHidden = !vm.titleHidden;
          }
          // =========================
          vm.playVoice("autoPlay");
        });
      },
    });
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {
    document.body.removeEventListener("click", this.outPopClick);
  },
  destroyed() {},
  activated() {},
};
</script>
<style lang="less" scope>
/* @import url(); 引入公共css类 */
@import url("./step.less");
</style>
